package com.mars.algorithm;

/**
 * @Author King
 * @create 2020/7/30 17:42
 */
public class KingSearch {

    public static void main(String[] args) {
        int[] ss = new int[]{1, 5, 7, 34, 78, 90, 101, 122, 345};
        int index = tSearch(ss, 7);
        if (index == -1) {
            System.out.println("#######不存在查找的元素######");
        } else {
            System.out.println("###查找的元素为:" + ss[index]);
        }


        int index2 = tSearch(ss, 127);
        if (index2 == -1) {
            System.out.println("#######递归不存在查找的元素######");
        } else {
            System.out.println("###递归查找的元素为:" + ss[index2]);
        }

    }

    /**
     * 二分查找
     *
     * @param array
     * @param target
     * @return
     */
    private static int tSearch(int[] array, int target) {
        int lo = 0;
        int hi = array.length - 1;
        while (lo <= hi) {
            int mid = lo + (hi - lo) / 2;
            if (array[mid] == target) {
                return mid;
            }
            if (array[mid] < target) {
                lo = mid + 1;
            }
            if (array[mid] > target) {
                hi = mid - 1;
            }
        }
        return -1;
    }


    private static int dtSearch(int[] array, int lo, int hi, int target) {
        if (lo > hi) {
            return -1;
        }
        int mid = lo + (hi - lo) / 2;
        if (array[mid] == target) {
            return mid;
        }
        if (array[mid] < target) {
            return dtSearch(array, mid + 1, hi, target);
        } else {
            return dtSearch(array, lo, hi - 1, target);
        }
    }
}
